﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Help;
using Model;
using System.Data.Entity.Validation;

namespace BLLA
{
    public partial class Order_Eva_T : BaseBLL<Model.Order_Eva_T>, IBLL.IOrder_Eva_TBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();
        IBLL.IBLLSession bl = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");

        /// <summary>
        /// 查询所有商户的评价管理信息
        /// </summary>
        /// <param name="MerID">商户ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string GetOrder_Eva(int pageIndex, int pageSize, string MerID, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion
                #region 执行操作
                List<Model.View_Order_Eva> ls = new List<Model.View_Order_Eva>();
                ls = bl.IView_Order_EvaBLL.GetListBy("SELECT *  FROM View_Order_Eva where MerID='" + MerID + "' and EvaState=1");
                if (ls != null & ls.Count > 0)
                {
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.total = ls.Count;
                    result.rows = ls.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
                #endregion
                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW(" 查询所有商户的评价管理信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }
        #region 获得菜品评论
        /// <summary>
        /// 获得菜品评论
        /// </summary>
        /// <param name="DishesID"></param>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public string GetDIshEva(string DishesID, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.View_Order_Dishes Dish = base.DBSession.IView_Order_DishesDAL.GetListBy(u => u.DishesID == DishesID).First();
                List<Model.View_Order_Eva> EvaList0 = base.DBSession.IView_Order_EvaDAL.GetListBy(u => u.DishesID == DishesID & u.EvaState == 1);
                List<Model.View_Order_Eva> EvaList = (from m in EvaList0 orderby m.EvaTime descending select m).ToList();
                //if (EvaList.Count > 0)
                //{
                result.BS = "1";
                result.Msg = "查询成功";
                result.rows = new Model.DishInfo { Dish = Dish, EvaList = EvaList };
                result.total = EvaList.Count;
                //}
                //else
                //{
                //    result.BS = "0";
                //    result.Msg = "查询不到数据";
                //    result.total = EvaList.Count;
                //}
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("查询菜品评论失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "查询菜品评论失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }
        #endregion

        /// <summary>
        /// 模糊查询商户的评价管理信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="FormID">订单ID，当入参为空时，表示查询所有订单</param>
        /// <param name="DishesNmae">菜品名，当入参为空时，表示查询所有菜品名</param>
        /// <param name="EvaStars">星级，当入参为空时，表示查询所有星级</param>
        /// <param name="MerID">商户ID</param>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public string GetOrder_EvaByPara(int pageIndex, int pageSize, string FormID, string DishesNmae, string EvaStars, string MerID, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion
                #region 执行操作
                List<Model.View_Order_Eva> ls = new List<Model.View_Order_Eva>();

                string dishes = "", formid = "", starts = "";
                if (FormID != "" && FormID != null)
                {
                    formid = " and  FormID ='" + FormID + "' ";
                }
                if (DishesNmae != "" && DishesNmae != null)
                {
                    dishes = " and DishesNmae like '%" + DishesNmae + "%' ";
                }
                if (EvaStars != "" && EvaStars != null)
                {
                    starts = " and  EvaStars=" + EvaStars + " ";
                }

                ls = bl.IView_Order_EvaBLL.GetListBy("SELECT *  FROM View_Order_Eva where MerID='" + MerID + "' " + formid + dishes + starts + "and EvaState=1");
                if (ls != null & ls.Count > 0)
                {
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.total = ls.Count;
                    result.rows = ls.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
                #endregion
                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW(" 查询所有商户的评价管理信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }

        /// <summary>
        /// 更新所有商户的评论管理信息（只允许修改BZ信息）
        /// </summary>
        /// <param name="OperID">操作员ID</param>
        /// <param name="json">更新信息</param>
        /// <param name="tag">操作标签（1：新增；2：修改；3：删除）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string SetOrder_Eva(int OperID, string json, int tag, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.Order_Eva_T info = ParseClass<Model.Order_Eva_T>.StrDeserialize(json, RETID);
                string T = "";
                int ret = -1;
                // 根据操作标签Tag判断是什么操作
                switch (2)
                {
                    //case 1:
                    //    T = "新增";
                    //    break;
                    case 2:
                        T = "修改";
                        Model.Order_Eva_T tmp = base.GetListBy(u => u.EvaID == info.EvaID).First();
                        Help.FuZhi<Model.Order_Eva_T>.FZ(ref tmp, info);
                        ret = base.Modify(tmp);
                        break;
                    //case 3:
                    //    T = "删除";
                    //    break;
                }

                if (ret > 0)
                {
                    // 将操作记录到日志表中
                    Model.Order_OperationFlow_T Log = new Model.Order_OperationFlow_T();
                    Log.OperationTitle = "更新所有商户的评论管理信息（只允许修改BZ信息）";
                    Log.OperationText = T + "所有商户的评论管理信息（只允许修改BZ信息）成功";
                    Log.OperationType = "1F0006";
                    Log.OperationRes = "成功";
                    Log.OperationUser = OperID;
                    string str_log = os.StringOfObject(Log, RETID);
                    bool isSuccess = new Order_OperationFlow_T().AddOrder_OperationFlow(str_log, RETID);
                    if (!isSuccess)
                    {
                        WriteLog.WriteW("新增系统操作流水失败");
                    }
                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder errors = new StringBuilder();
                IEnumerable<DbEntityValidationResult> validationResult = ex.EntityValidationErrors;
                foreach (DbEntityValidationResult result in validationResult)
                {
                    ICollection<DbValidationError> validationError = result.ValidationErrors;
                    foreach (DbValidationError err in validationError)
                    {
                        errors.Append(err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                    }
                }
                //Console.WriteLine(errors.ToString());
                WriteLog.WriteW("SetOrder_Eva异常：" + errors.ToString());

            }
            catch (Exception ex)
            {
                WriteLog.WriteW("更新商户的订单状态和备注信息失败：" + ex.Message);
                result.BS = "-1";
                result.Msg = "更新失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }

        #region 添加订单评论
        /// <summary>
        /// 添加订单评论
        /// </summary>
        /// <param name="FormID">订单ID</param>
        /// <param name="EvaTxt">评论内容</param>
        /// <param name="EvaStars">评论星数</param>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public string AddOrderEva(string FormID, string[] FormDishesID, string EvaTxt, int EvaStars, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                if (FormDishesID != null && FormDishesID.Length > 0)
                {
                    int formid = int.Parse(FormID);
                    Model.Order_Form_T OForm = base.DBSession.IOrder_Form_TDAL.GetListBy(u => u.FormID == formid).First();
                    Model.Order_Mer_T Mer = base.DBSession.IOrder_Mer_TDAL.GetListBy(u => u.MerID == OForm.FormMerID).First();

                    string[] DishIDs = OForm.FormDishesID.Split(',');
                    Mer.StarCount = Mer.StarCount + DishIDs.Length * EvaStars;
                    Mer.EvaCount = Mer.EvaCount + DishIDs.Length;
                    if (!(base.DBSession.IOrder_Mer_TDAL.Modify(Mer) > 0))
                    {
                        result.BS = "-2";
                        result.Msg = "添加商户销售量失败";
                        return os.StringOfObject(result, RETID);
                    }
                    List<Model.Order_Eva_T> EvaList = new List<Model.Order_Eva_T>();
                    string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                    foreach (var item in FormDishesID)
                    {
                        Model.Order_Eva_T tmp = new Model.Order_Eva_T();
                        Model.Order_Dishes_T dis_t = base.DBSession.IOrder_Dishes_TDAL.GetListBy(u => u.MerID == OForm.FormMerID & u.DishesID == item & u.DishesTypeState == 1).First();
                        dis_t.DishesEvaNun += 1;
                        if (EvaTxt != null & EvaTxt != "")
                        {
                            dis_t.DishesEvaTxt += 1;
                        }
                        dis_t.DishesEvaX += EvaStars;
                        tmp.AccID = OForm.AccID;
                        tmp.DishesID = item;
                        tmp.FormID = FormID;
                        tmp.MerID = OForm.FormMerID;
                        tmp.EvaTxt = EvaTxt;
                        tmp.EvaTime = time;
                        tmp.EvaStars = EvaStars;
                        tmp.EvaState = 1;
                        EvaList.Add(tmp);
                        base.DBSession.IOrder_Dishes_TDAL.Modify(dis_t);

                    }

                    for (int i = 0; i < FormDishesID.Length; i++)
                    {
                        string id = FormDishesID[i];
                        Model.Order_Dishes_T dish = base.DBSession.IOrder_Dishes_TDAL.GetListBy(u => u.MerID == OForm.FormMerID & u.DishesID == id & u.DishesTypeState == 1).First();
                        dish.DishesGood += 1;

                        base.DBSession.IOrder_Dishes_TDAL.Modify(dish);
                    }

                    if (base.Add(EvaList) > 0)
                    {
                        result.BS = "1";
                        result.Msg = "添加成功";
                        OForm.IsEva = 1;
                        base.DBSession.IOrder_Form_TDAL.Modify(OForm);
                    }
                    else
                    {
                        result.BS = "-1";
                        result.Msg = "添加失败";
                    }
                }
                else
                {
                    result.BS = "-1";
                    result.Msg = "请选择要评论的菜品";
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("新增用户评价失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "更新失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }
        #endregion
    }
}
